#!usr/bin/node

const Router = require('koa-router'),
      router = new Router(),
      mysql = require('mysql2/promise');

class ResData {
  constructor() {
    this.code = 0;
    this.msg = 'pk';
    this.count = 0;
    this.data = '';
  }
};

let con = '';

(async ()=>{
  con = await mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'ddd',
    database:'demo'
  })
})();

router.prefix('/api/authors');

router.get('/',async (ctx,next) => {
  const {page,limit} = ctx.query;
  const userAgent = ctx.header['user-agent'];

  const res = new ResData();

  const sql = `select * from authors order by id limit ${(page-1)*limit},${limit};`,
  sqlCount = `select count(id) as count from authors;`;

  let [rows] = await con.query(sql);
  res.data = rows;

  //rows = await con.query(sqlCount);
  //res.data = rows[0].count;

  console.log(`user-agent:${userAgent}`);
  console.log(`得到漫画书作者列表,page:${page},limit:${limit}`);
  ctx.body = res;
});

router.get('/:authorName',async (ctx,next) => {
  const {authorName} = ctx.params;
  console.log(`按作者名称查询:${authorName}`);

  const res = new ResData();

  ctx.body = res;
});

router.post('/',async (ctx,next) => {
  const {authorName} = ctx.request.body;
  console.log(`添加新的漫画书作者信息:${authorName}`);

  const res = new ResData();

  ctx.body = res;
});

router.put('/:id',async (ctx,next) => {
  const {id} = ctx.params,
        {authorName} = ctx.request.body;
  console.log(`修改某id = ${id}的漫画书作者信息:${authorName}`);

  const res = new ResData();

  ctx.body = res;
});

router.delete('/:id',async (ctx,next) => {
  const {id} = ctx.params;
  console.log(`删除某id = ${id}的漫画书作者信息`);

  const res = new ResData();

  ctx.body = res;
});

module.exports = router;
